<?php

namespace App\Models;

use App\Enums\RefundState;
use App\Events\OrderRefundedEvent;
use App\Jobs\OrderRefund;
use App\Models\Traits\BelongsToApplication;
use App\Traits\AutoCreateOrderNo;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class Refund extends Model
{
    use AutoCreateOrderNo,
        BelongsToApplication;

    protected $casts = [
        'resource' => 'json',
        'refunded_at' => 'datetime',
        'state' => RefundState::class,
    ];

    protected static function boot(): void
    {
        parent::boot();

        self::created(function (Refund $refund) {
            OrderRefund::dispatch($refund);
        });
    }

    public function order(): BelongsTo
    {
        return $this->belongsTo(Order::class);
    }

    /**
     * Notes   : 退款成功操作
     *
     * @Date   : 2024/7/17 上午9:18
     * @Author : <Jason.C>
     */
    public function refunded(array $resource): void
    {
        $this->state = RefundState::SUCCESS;
        $this->resource = $resource;
        $this->refunded_at = now();
        $this->save();
        OrderRefundedEvent::dispatch($this);
    }
}
